<?
    header('Content-type: text/html; charset=utf-8');
    $error = 0;
        $errormessage = '';
    if (isset($_GET['error'])) {
        $error = $_GET['error'];
    }
    if ($error != '0') {
        $error = 1;
        $errormessage = 'test error message';
    }
    $where = ' where (1 = 1)';
    if (isset($_GET['categoryid'])) {
        $categoryid = $_GET['categoryid'];
        $where = $where." and (categoryid = '$categoryid')";
    }
    if (isset($_GET['userid'])) {
        $userid = $_GET['userid'];
        $where = $where." and (user_id = '$userid')";
    }
    if (isset($_GET['photoid'])) {
        $photoid = $_GET['photoid'];
        $where = $where." and (id = '$photoid')";
    }
    if (isset($_GET['search'])) {
        $search = '%'.$_GET['search'].'%';
        $where = $where." and (tags like '$search')";
    }

    $connection = mysql_connect ('localhost', 'zorik_if039', '9731')
	or die ('Unable to connect!');
	mysql_select_db('zorik_if039') or die (mysql_error());
	mysql_query("set character_set_client='utf8'"); 
	mysql_query("set character_set_server='utf8'"); 
	mysql_query("set character_set_results='utf8'"); 
	mysql_query("set collation_connection='utf8_unicode_ci'");

	$query = "select added, id, title, filename, description, tags, user_id, longitude, latitude, date, categoryid, AVG(rating) rating from (
    SELECT p . * , IFNULL( r.rating, 0 ) rating
    FROM photo AS p
    LEFT JOIN rating AS r ON ( p.id = r.photoid )
    ) AS pr ".$where.
    " group by added, tags, user_id, longitude, latitude, date, filename, description, title, categoryid, id
    order by added desc";
	$res = mysql_query($query) or die(mysql_error());
	$rows = array();
	while($r = mysql_fetch_assoc($res)) {
	    $rows[] = $r;
	}
        if ($error == 0) {
	    $categoryList = (object) array('error' => $error, 'errormessage' => $errormessage, 'data' => $rows);
        } else {
            $categoryList = (object) array('error' => $error, 'errormessage' => $errormessage, 'data' => '');
        }
	echo json_encode($categoryList);
	mysql_close($connection);
?>